
 
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using ST.Data;
using Microsoft.Extensions.Configuration;
using NLog.Web;
using ST.Simulator.Tasks;
using ST.Simulator.Trans; // 添加这个引用
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

 
var services = builder.Services;
services.AddControllers()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Converters.Clear();
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    //options.JsonSerializerOptions.IgnoreNullValues = true;
                    options.JsonSerializerOptions.DefaultIgnoreCondition =
                        System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
                    options.JsonSerializerOptions.ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip;
                    options.JsonSerializerOptions.DefaultBufferSize = 1024;
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                })
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = null;
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore; // 添加这行
                    options.SerializerSettings.Converters = new List<JsonConverter>
                    {
                        new ST.Core.Util.JSON.LongToStringConverter(),
                        new  ST.Core.Util.JSON.CustomDateTimeConverter(),
                        new  ST.Core.Util.JSON.NullStringConverter()
                    };
                });
// 确保使用AddDbContextFactory正确配置
services.AddDbContextFactory<ST.Data.AppDbContext>(options =>
{
    var dbPath = Path.Combine(builder.Environment.ContentRootPath, "Database.db");
    var str = $"Data Source={dbPath}";

    options.UseSqlite( str); // 添加ServiceLifetime.Singleton
}, ServiceLifetime.Scoped);
    

services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
services.AddHostedService < ST.Simulator.Tasks.TransTask> ();
services.AddScoped<TCPTrans>();
services.AddScoped<UdpTrans>();
services.AddScoped<PortTrans>();
// 添加 NLog  
builder.Logging.ClearProviders();
//builder.Logging.SetMinimumLevel(LogLevel.Debug);  
//NLogBuilder.ConfigureNLog("nlog.config");  
builder.Host.UseNLog();


var app = builder.Build();

ST.Core.Util.ServicesUtil.Services=app.Services;
// 初始化数据库
using (var scope = app.Services.CreateScope())
{
    var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<ST.Data.AppDbContext>>();
    using (var dbContext = dbContextFactory.CreateDbContext())
    {
        dbContext.Database.EnsureCreated();

        var d = DateTime.Now.AddDays(-3);
        var lid = ST.Core.Util.IdUtil.ConvertDateTimeToId(d);
        var t = dbContext.Database.ExecuteSql($"DELETE FROM ProtocolSimLog WHERE ID<{lid}");
    }
}



// 使用配置中的缓存时间
var cacheDuration = builder.Configuration.GetValue<int>("AppSettings:CacheDuration");
var wwwroot = Path.Combine(builder.Environment.ContentRootPath, "wwwroot");
if(builder.Environment.IsDevelopment()){
     
}
app.UseStaticFiles(new StaticFileOptions
{
    ServeUnknownFileTypes = builder.Configuration.GetValue<bool>("AppSettings:StaticFiles:ServeUnknownFileTypes"),
    DefaultContentType = builder.Configuration.GetValue<string>("AppSettings:StaticFiles:DefaultContentType"),
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append("Cache-Control", $"public,max-age={cacheDuration}");
    },
    FileProvider = new PhysicalFileProvider(wwwroot),
});

app.UseRouting();


// 添加自定义中间件
app.UseMiddleware<ST.Core.WEB.MyMiddle>();

app.MapControllers();

 

app.Run();
